package com.sky.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import com.alibaba.fastjson.JSON;
import com.sky.context.BaseContext;
import com.sky.entity.Category;
import com.sky.entity.Dish;
import com.sky.mapper.CategoryMapper;
import com.sky.mapper.ReportMapper;
import lombok.extern.slf4j.Slf4j;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

// 有个很重要的点 DemoDataListener 不能被spring管理，要每次读取excel都要new,然后里面用到spring可以构造方法传进去
@Slf4j
public class DishImportListener implements ReadListener<DishImport> {

    /**
     * 每隔5条存储数据库，实际使用中可以100条，然后清理list ，方便内存回收
     */
    private static final int BATCH_COUNT = 100;
    /**
     * 缓存的数据
     */
    private List<DishImport> dishImports = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
    /**
     * 假设这个是一个DAO，当然有业务逻辑这个也可以是一个service。当然如果不用存储这个对象没用。
     */
    private ReportMapper reportMapper;
    private CategoryMapper categoryMapper;

    public DishImportListener(ReportMapper reportMapper, CategoryMapper categoryMapper) {
        this.reportMapper = reportMapper;
        this.categoryMapper = categoryMapper;
    }

    /**
     * 这个每一条数据解析都会来调用
     *
     * @param data    one row value. Is is same as {@link AnalysisContext#readRowHolder()}
     * @param context
     */
    @Override
    public void invoke(DishImport data, AnalysisContext context) {
        log.info("解析到一条数据:{}", JSON.toJSONString(data));
        dishImports.add(data);
        // 达到BATCH_COUNT了，需要去存储一次数据库，防止数据几万条数据在内存，容易OOM
        if (dishImports.size() >= BATCH_COUNT) {
            saveData();
            // 存储完成清理 list
            dishImports = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
        }
    }

    /**
     * 所有数据解析完成了 都会来调用
     *
     * @param context
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        // 这里也要保存数据，确保最后遗留的数据也存储到数据库
        saveData();
        log.info("所有数据解析完成！");
    }

    /**
     * 加上存储数据库
     */
    private void saveData() {
        ArrayList<Dish> dishes = new ArrayList<>();
        dishImports.forEach(dishImport -> {
            Dish dish = new Dish();
            Category category = categoryMapper.getCategoryIdByName(dishImport.getCategoryName());
            if (category != null) {
                Long categoryId = category.getId();
                dish.setCategoryId(categoryId);
                dish.setName(dishImport.getName());
                dish.setPrice(new BigDecimal(dishImport.getPrice()));

            }
            if ("起售".equals(dishImport.getStatus())) {
                dish.setStatus(1);
            } else {
                dish.setStatus(0);
            }
            dish.setCreateTime(LocalDateTime.now());
            dish.setUpdateTime(LocalDateTime.now());
            dish.setCreateUser(BaseContext.getCurrentId());
            dish.setUpdateUser(BaseContext.getCurrentId());
            dishes.add(dish);
        });
        List<Dish> dishList = dishes.stream().filter(dish -> dish.getCategoryId() != null).collect(Collectors.toList());

        reportMapper.insertBatch(dishList);
        log.info("存储数据库成功！");
    }
}